/************************************
             组件介绍
 * 【外框说明】
 * 整个组件竖向分为12格
 * 外层框使用class名称："g-drag"  
 * 例如：<div class="g-drag"></div> *
 * 调用内容编辑请添加class名称："g-drag-edit"
 * 例如：<div class="g-drag g-drag-edit"></div>
 * 若要显示网格编辑时请添加class：g-drag-edit-grid
 * 
 * 【模块说明】
 * 模块请使用class名称："g-drag-item"
 * 模块有四种自定义属性，例如： grid-x="0" grid-y="0" grid-w="6" grid-h="3" 
 * grid-x：网格x轴坐标
 * grid-y: 网格y轴坐标
 * grid-w：所占横向格子数量
 * grid-h：所占横向格子数量
 * 默认模块内没有边框也没有底色，内容全部为空，间距为0，可在模块内嵌入其它dom元素增加间距或者样式
 * 也可以使用默认自带模块
 * 模块示例：
    <div class="g-drag-item" grid-x="0" grid-y="0" grid-w="6" grid-h="3">
      <div class="g-drag-car">
          自定义内容区域
      </div>
    </div>
 * 
 * 【全局变量】
 * gridHeight ：网格每格高度(单位：px)
 * need_move_distance : 拖拽时鼠标移动超过几个格子触发移动
 * allItemsData: 全局定义元素，编辑时记录编辑区初始化，方便重置与保存
 * fixedHeight:是否使用固定高度，若为否 grid-h 将不起作用
 * move_event_btn:触发移动事件的元素class名称，若为空，则拖拽整个模块
 * 
 ************************************/
var gridHeight = 100;
var fixedHeight = false; //是否使用固定高度，若为否 grid-h 将不起作用
var need_move_distance = 1;
var allItemsData=[];
var move_event_btn = "move_event_btn";//触发移动的元素class名称
var moduleColumnWDTH = [4,4,4],moduleColumn = [0,4,8];

//模块排列调整
async function filtercopyDragElAll(){
  var ModragEl = document.querySelector(".g-drag-item-shadow");
  var allitem = document.querySelectorAll(".g-drag > .g-drag-item:not(.dragEl)");
  var allcolumn = [];
  if(moduleColumn && moduleColumn.length>0){
    allcolumn = moduleColumn
  }else{
    allitem.forEach(val=>{
      if(allcolumn.indexOf(val.getAttribute("grid-x"))<0){
        allcolumn.push(val.getAttribute("grid-x"))
      }
    });
  };
  allcolumn.forEach((Iv,ind)=>{
    var allthiscolumn = document.querySelectorAll(".g-drag > .g-drag-item[grid-x='"+Iv+"']:not(.dragEl)");
    var willMoveOldItems = height_rank(allthiscolumn);
    var ModragElSet=false;
    willMoveOldItems.forEach((val,index)=>{
      if(index>0){
        val.setAttribute("grid-y",willMoveOldItems[index-1].getAttribute("grid-y")*1+willMoveOldItems[index-1].getAttribute("grid-h")*1)
      }else{
        val.setAttribute("grid-y",0+"")
      }
    })
  });
  drag_itmes_ready()
};

//按照模块高度排序
function height_rank(all){
  var list = [];
  all.forEach(val=>{
    list.push(val)
  });
  list.sort(function(a,b){
    var sort1 = a.getAttribute("grid-y")*1;
    var sort2 = b.getAttribute("grid-y")*1 ;
    return sort1 - sort2
  });
  return list;
};

//拖拽动作
function copyDragEl_move(){
  let mouse_startY = event.clientY;//移动起始坐标X
  let mouse_startX = event.clientX;//移动起始坐标Y
  let move_Len = parseInt(document.querySelector(".g-drag-edit").clientWidth/12);//网格宽度为拖拽模块外开框/12、高度变量 gridHeight
  var copyEl = document.querySelector(".dragEl");//拖拽的元素
  var ModragEl = document.querySelector(".g-drag-item-shadow");//拖拽元素的投影
  var copyElLft = ModragEl.offsetLeft;//拖拽的元素相对父级偏移x
  var copyElTop = ModragEl.offsetTop;//拖拽的元素相对父级偏移Y
  var condition_X = move_Len*need_move_distance; //左右移动多少距离触发移动
  var condition_y = gridHeight*need_move_distance;//上下移动多少距离触发移动
  var me_start_x=event.clientX,me_start_y=event.clientY;//拖拽元素的投影起始坐标，每次移动后更新直到拖拽结束
  var allcolumn= [];
  var allWDTH= [];
  // console.log("转换！！！",moduleColumn)
  if(moduleColumn && moduleColumn.length>0){
    allcolumn= moduleColumn;
    allWDTH = moduleColumnWDTH;
  }else{
    document.querySelectorAll(".g-drag-item[grid-y='0']").forEach(val=>{
      if(allcolumn.indexOf(val.getAttribute("grid-x")*1)<0){
        allcolumn.push(val.getAttribute("grid-x")*1);
        allWDTH.push(val.getAttribute("grid-W")*1);
      }
    });
  };
  var go_to_move_run = (l)=>{
      me_start_y=event.clientY
      me_start_x=event.clientX;
      if(l){
        filtercopyDragElAll(ModragEl)
      }else{
        drag_itmes_ready()
      };
  };
  // ModragEl.style.height = gridHeight+"px";
  
  document.onmousemove = () =>{
    let mouseY = event.clientY;
    let mouseX = event.clientX;
    var meX = Math.abs(mouseX)-Math.abs(me_start_x);
    var meY = Math.abs(mouseY)-Math.abs(me_start_y);

    copyEl.style.left = copyElLft+(Math.abs(mouseX)-Math.abs(mouse_startX))+"px";
    copyEl.style.top = copyElTop+Math.abs(mouseY)-Math.abs(mouse_startY)+"px";
    var isMx = Math.abs(meX)>condition_X;
    var isMy = Math.abs(meY)>condition_y && ModragEl.getAttribute("grid-y")*1 >= 0;
    if(isMx){
      // var toX = meX>0?ModragEl.getAttribute("grid-x")*1+ModragEl.getAttribute("grid-w")*1:ModragEl.getAttribute("grid-x")*1-ModragEl.getAttribute("grid-w")*1;
      var toX = parseInt(copyEl.offsetLeft/move_Len);
      var hasCol = allcolumn.indexOf(toX);
      if(meX >0 &&  copyEl.getBoundingClientRect().left >= ModragEl.getBoundingClientRect().left + move_Len*need_move_distance
        || meX <0 &&  mouseX <= ModragEl.getBoundingClientRect().left *move_Len){
          // && allWDTH[hasCol]*1==ModragEl.getAttribute("grid-w")*1
        if(hasCol >-1  && toX+ModragEl.getAttribute("grid-w")*1 <=12){
          ModragEl.setAttribute("grid-x",toX+"");
          ModragEl.style.left = toX*8.3333333333333333+"%";
          return go_to_move_run("l")
        }
      }
    };
    if(isMy){
      var allMEl =  height_rank(document.querySelectorAll(".g-drag-edit > .g-drag-item[grid-x='"+ModragEl.getAttribute("grid-x")*1+"']:not(.dragEl):not(.g-drag-item-shadow)"));
      if(meY<0){
        for(var i=allMEl.length-1;i>=0;i--){
          var vl = allMEl[i];
          if(
            mouseY <= ModragEl.getBoundingClientRect().top &&
            ModragEl.getAttribute("grid-y")*1-1 >= vl.getAttribute("grid-y")*1
            && ModragEl.getAttribute("grid-y")*1-1 <= vl.getAttribute("grid-y")*1+vl.getAttribute("grid-h")*1
          ){
            var copygrid_y = vl.getAttribute("grid-y")*1;
            var copygrid_h = ModragEl.getAttribute("grid-h")*1;
            ModragEl.setAttribute("grid-y",copygrid_y);
            vl.setAttribute("grid-y",copygrid_y+copygrid_h);
            // drag_itme_grid(ModragEl);drag_itme_grid(vl)
            return go_to_move_run();
          }
        };
      }else{
        for(var i=0;i<allMEl.length;i++){
          var vl = allMEl[i];
          if(
            // mouseY >= ModragEl.getBoundingClientRect().top+ModragEl.clientHeight &&
            vl.getAttribute("grid-y")*1 <= ModragEl.getAttribute("grid-y")*1+ModragEl.getAttribute("grid-h")*1+1
            && vl.getAttribute("grid-y")*1 >= ModragEl.getAttribute("grid-y")*1+1){
            var copygrid_y = ModragEl.getAttribute("grid-y")*1;
            var copygrid_h = vl.getAttribute("grid-h")*1;
            ModragEl.setAttribute("grid-y",copygrid_y+copygrid_h);
            vl.setAttribute("grid-y",copygrid_y);
            return go_to_move_run();
          }
        }
      }
    }
  }
};

//模块重置宽高以及距离、添加拖拽事件
function item_drag(val){
  var move_Btn;
  if(val.className.indexOf(move_event_btn) > -1){
    move_Btn = val
  }else{
    move_Btn = val.querySelector("."+move_event_btn);
  };
  if(move_Btn){
    move_Btn.onmousedown = ()=>{
      if(document.querySelector(".g-drag-edit")===undefined || document.querySelector(".g-drag-edit")===null){return false};
      var copyEl = document.createElement("div");
      val.className+=" dragEl";
      copyEl.setAttribute("grid-x",val.getAttribute("grid-x"));
      copyEl.setAttribute("grid-y",val.getAttribute("grid-y"));
      copyEl.setAttribute("grid-w",val.getAttribute("grid-w"));
      copyEl.setAttribute("grid-h",val.getAttribute("grid-h"));
      copyEl.className = "g-drag-item g-drag-item-shadow";
      
      val.parentNode.prepend(copyEl);
      
      // copyEl.style.left = val.getAttribute("grid-x")*8.3333333333333333333+"%";
      // copyEl.style.top = val.style.top;
      drag_itme_grid(copyEl);
      document.onmousemove = () =>{
          return copyDragEl_move()
      }
    };
  }
};

// 调整单个组件高度
function drag_itme_grid(val){
  var contenWidth = document.querySelector(".g-drag")
  val.style.top = val.getAttribute("grid-y")*gridHeight +"px";
  val.style.left = val.getAttribute("grid-x")*(100/12) +"%";
  val.style.width = val.getAttribute("grid-w")*(100/12) +"%";
  val.style.height = "auto";
  if(!fixedHeight && val.className.indexOf("g-drag-item-shadow")<0){
    // console.log("fixedHeight:",fixedHeight)
    if(val.clientHeight/gridHeight<1){
      val.setAttribute("grid-h",1)
    }else{
      val.setAttribute("grid-h",val.clientHeight/gridHeight)
    }
  };
  val.style.height = val.getAttribute("grid-h")*gridHeight +"px";
};

//获取网格数列数量
function grid_columns(){
  var maxT=0;
  document.querySelectorAll(".g-drag-item:not(.dragEl)").forEach((val,index)=>{
    drag_itme_grid(val);
      if(val.getAttribute("grid-y")*1+val.getAttribute("grid-h")*1>maxT){
      maxT = val.getAttribute("grid-y")*1+val.getAttribute("grid-h")*1;
    }
  });
  return maxT;
};

//调整所有组件宽高以及位置
function drag_itmes_ready(){
  var drag_content_el = document.querySelector(".g-drag");
  drag_content_el.style.height = grid_columns()*gridHeight+"px";
};

//初始化网格以及模块、以及添加网格以及元素样式
var initialization_drag = function(FH,CW,CX){
  if(FH!==undefined && FH !==null){fixedHeight = FH;};
  if(CX!==undefined && CX !==null){moduleColumn = CX;};
  if(CW!==undefined && CW !==null){moduleColumnWDTH = CW;};
  filtercopyDragElAll();
  var cssText = `
//-------grid_drag_style------
.class{}
.g-drag{display:flex !important;flex:1 !important;;position:relative !important;;flex-wrap:wrap !important;
  box-sizing: border-box !important;overflow: hidden;}
.g-drag-edit > *{z-index: 1;}
.g-drag-edit-grid::before{
  content: "";
  width: 100%;
  height: 100%;
  display: block;
  position: absolute;
  top: 0px;
  background-image: linear-gradient(0deg,#ffffff 1px, transparent 0.0001px), linear-gradient(90deg,#ffffff 1px, transparent 0.0001px);
  background-size: calc(8.33333333333333%) 100px;
  background-attachment: local, scroll;
  overflow-y: overlay;
  border-top: 1px #ffffff solid;
  border-bottom: 1px #ffffff solid;
  border-right: 1px #ffffff solid;
  // box-shadow: inset 0px 0px 5px rgba(0,0,0,0.2);
  background-color: rgba(0,0,0,0.08);
  transition: all 300ms;
}
.g-drag-edit *{-moz-user-select:none;-webkit-user-select:none;-ms-user-select:none;-khtml-user-select:none;
  user-select:none;}
  
// .g-drag-edit .g-drag-item{cursor: move;}
// .g-drag-edit .g-drag-item:hover::before{content:"";width: 100%;height: 100%;position: absolute;top:0;left: 0;
//   background-color:rgba(0,0,0,0);z-index: 9999999;}
// .g-drag-edit{background-color: rgba(0,0,0,0.0);border: 0px rgba(0,0,0,0.1) solid;}

.dragEl{z-index: 9999999;}.g-drag-item:not(.dragEl){transition: all 300ms;}
.g-drag-item{display: block;position: absolute;box-sizing: border-box;}
.g-drag-item-shadow{border:2px rgba(0,0,0,0.2) dashed;position:absolute;background-color:rgba(0,0,0,0.1);
  transition: all 300ms;}
.g-drag-car{display: flex;position: absolute;flex: 1;width: calc(100% - 20px);height: calc(100% - 20px);
  margin: 10px;box-sizing: border-box;background-color: #ffffff;margin:10px;border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.06);border:1px #dddddd solid;overflow:hidden;word-wrap:break-word;}
    `;
  if(!move_event_btn || move_event_btn===""){
    cssText+=".g-drag-edit .g-drag-item{cursor: move;}";
  }else{
    cssText+=("."+move_event_btn+"{cursor: move}.g-drag-edit .g-drag-item{cursor: auto;}")
  };
  var head = document.head || document.getElementsByTagName('head')[0];
  if(document.querySelector('head style[grid_drag_style]')){
    document.querySelector('head style[grid_drag_style]').innerText = cssText;
  }else{
    var style = document.createElement('style');
      style.type = 'text/css';
      style.setAttribute("grid_drag_style",true);
      if(style.styleSheet){ //IE
        var func = function(){
            try{style.styleSheet.cssText = cssText}catch(e){}
        };
        if(style.styleSheet.disabled){
            setTimeout(func,10);
        }else{
            func();
        }
      }else{
          var textNode = document.createTextNode(cssText);
          style.appendChild(textNode);
      }
      head.appendChild(style);
  };

  document.querySelectorAll(".g-drag-item:not(.dragEl)").forEach((val,index)=>{
    item_drag(val);
  });
  filtercopyDragElAll();
  document.addEventListener("mouseup",function(){
    var ModragElEl = document.querySelector(".g-drag-item-shadow");
    document.onmousemove = null;
    var dragEl = document.querySelector(".dragEl");
    var ModragAll = document.querySelectorAll(".g-drag-item-shadow");
    if(dragEl && ModragElEl){
        dragEl.setAttribute("grid-x",ModragElEl.getAttribute("grid-x"));dragEl.setAttribute("grid-y",ModragElEl.getAttribute("grid-y"));
        dragEl.setAttribute("grid-w",ModragElEl.getAttribute("grid-w"));dragEl.setAttribute("grid-h",ModragElEl.getAttribute("grid-h"));
        // drag_itme_grid(dragEl);
        dragEl.classList.remove("dragEl");
    };
    if(ModragAll && ModragAll.length > 0){
      ModragAll.forEach(ModragEl=>{
        ModragEl.parentElement.removeChild(ModragEl);
        drag_itmes_ready()
      })
    }
  });
};

window.addEventListener("resize",function(){
  initialization_drag()
})

/************************************
 * 若使用在头部引入该文件请使用在dom加载后调用初始化函数 *
 ************************************/
/**
 window.addEventListener("load",function(){
  initialization_drag()
});
**/

/************************************
 * import引入方式 *
 ************************************/
export default {initialization_drag,filtercopyDragElAll};

/************************************
 * require调用 *
 ************************************/
// module.exports = initialization_drag;